package org.cfk.delaytasktutorial.handler;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.cfk.delaytasktutorial.annotation.LazyJob;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;


import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class LazyJobHandlerContent implements CommandLineRunner {

    @Resource
    private ApplicationContext applicationContext;
    private final Map<String, Method> annotatedMethods = new HashMap<>();

    @Override
    public void run(String... args) {
        log.info("应用启动扫描延迟任务方法");
        scanAndCacheAnnotatedMethods();
    }

    private void scanAndCacheAnnotatedMethods() {
        log.info("开始扫描异步延迟任务方法");
        String[] beanNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            Object bean = applicationContext.getBean(beanName);
            Class<?> clazz = bean.getClass();
            for (Method method : clazz.getDeclaredMethods()) {
                LazyJob annotation = AnnotationUtils.findAnnotation(method, LazyJob.class);
                if (annotation != null) {
                    annotatedMethods.put(annotation.value(), method);
                }
            }
        }
        log.info("完成扫描异步延迟任务方法，共找到 {} 个方法", annotatedMethods.size());
    }

    public Method getByName(String name) {
        Method method = annotatedMethods.get(name);
        if (Objects.isNull(method)) {
            scanAndCacheAnnotatedMethods();
            method = annotatedMethods.get(name);
        }
        return method;
    }
}